// pages/waveTest/waveTest.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    testFrame:0,
    audioCtx:null,
    analyser:null,
    arr:[{width:20},{width:60},{width:30}],
    //aiurl:"https://u88368-9b5c-68b3652e.westb.seetacloud.com:8443/file=/tmp/gradio/747733af2336c2f5a87b1d174dce5e3a21ed50f8/audio.wav",
    aiurl:"https://u88368-9b5c-68b3652e.westb.seetacloud.com:8443/file=/tmp/gradio/474dfb954ed6c86cd95764a5194ddc0df40bd6d2/audio.wav",
    ///
    clipPath:"",
    clipArr:[[50,50]],
    rotation:90,
    timeId:0,
    cloudUrl:app.globalData.cloudUrl,
  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var audioCtx = wx.createWebAudioContext();
    this.setData({audioCtx:audioCtx});
    const loadAudio = (url) => {
      console.log(url);
      return new Promise((resolve) => {
        wx.request({
          url,
          responseType: 'arraybuffer',
          success: res => {
            //console.log('res.data', res.data)
            //let uint8Array = new Uint8Array(res.data);
            //var arr = new Array(uint8Array);
            //console.log('uint8Array=', uint8Array)
            //console.log('arr=', uint8Array)
            audioCtx.decodeAudioData(res.data, buffer => {
              resolve(buffer)
            }, err => {
              console.error('decodeAudioData fail', err)
              reject()
            })
          },
          fail: res => {
            console.error('request fail', res)
            reject()
          }
        })
      })
    }
    const play = () => {
      var _this = this;
      loadAudio(this.data.aiurl).then(buffer => {
        this.setData({audioCtx:audioCtx});
        let source = audioCtx.createBufferSource();
        source.buffer = buffer;

        //source.connect(audioCtx.destination);
        const analyser = audioCtx.createAnalyser();
        this.setData({analyser:analyser});
        source.connect(analyser);
        //analyser.fftSize = 512;
        //const bufferLength = analyser.fftSize;
        analyser.connect(audioCtx.destination);

        source.start();

        

        //console.log(buffer);
        
        //let f32 = buffer.getChannelData(0);
        //console.log(f32);

        //console.log(source);

        //this.onFrame();
        
        setInterval(_this.onFrame, 1000/60);
        //
        //const audioCtx = wx.createWebAudioContext();
        
        //console.log(analyser);
      }).catch(() => {
        console.log('fail')
      })
    }
    
    play();

    //var tid = setInterval(this.onTimer, 100);
    //this.setData({timeId:tid});
  },
  onTimer(){
    var rt = this.data.rotation;
    var vx = 50 + 50 * Math.cos(rt * Math.PI / 180);
    var vy = 50 + 50 * Math.sin(rt * Math.PI / 180);
    //console.log("vx="+vx+",vy="+vy);

    var arr = this.data.clipArr;
    arr.push([vx, vy]);
    //"polygon(50% 50%,50% 100%,25% 100%)"
    var str = "polygon(";
    for(var i=0; i<arr.length; i++){
      str += arr[i][0] + "% ";
      if(i == arr.length - 1){
        str += arr[i][1] + "%";
      }
      else{
        str += arr[i][1] + "%,";
      }
    }
    str += ")";
    //console.log("----angle="+rt+",vx="+vx+",vy="+vy);
    if(rt>=360+90){
      clearInterval(this.data.timeId);
    }
    rt += 2;

    this.setData({rotation:rt, clipArr:arr, clipPath:str});
  },
  
  onFrame(){
    /**var audioCtx = this.data.audioCtx;
    const analyser = audioCtx.createAnalyser();
    analyser.fftSize = 128;
    const bufferLength = analyser.fftSize;
    const dataArray = new Uint8Array(bufferLength);
    analyser.getByteTimeDomainData(dataArray);**/

    //const audioCtx = wx.createWebAudioContext();
    //const analyser = audioCtx.createAnalyser();
    //analyser.fftSize = 512;
    //const bufferLength = analyser.fftSize;
    const dataArray = new Uint8Array(107);
    var analyser = this.data.analyser;
    analyser.getByteTimeDomainData(dataArray);
    //console.log("-----------------------");
    //console.log(dataArray);
    
    var arr = this.data.arr;
    arr.length = 0;
    //console.log(dataArray);
    for(var i=0; i<dataArray.length; i++){
      var v = dataArray[i] / 128.0;
      // 计算波形点的纵坐标
      var y = v * 80;
      arr.push({width:y});
    }
    this.setData({arr:arr});
    return;
    var frame = this.data.testFrame;
    console.log("dsdssddsds" + (frame));
    frame ++;
    this.setData({testFrame:frame});
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})